package com.guozcc.gateway.autofilter.base;

import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
public abstract class AbstractGatewayRequestBaseFilter implements GatewayFilter, RewriteFunction<String, String>, HandlerRequestBody {

    private GatewayFilter requestFilter;

    public AbstractGatewayRequestBaseFilter(ModifyRequestBodyGatewayFilterFactory modifyRequestBody){
        this.requestFilter = modifyRequestBody.apply(new ModifyRequestBodyGatewayFilterFactory.Config()
                .setRewriteFunction(String.class, String.class, this));
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return requestFilter.filter(exchange, chain);
    }

    abstract public String handlerReqBody(ServerWebExchange serverWebExchange, String originBody);



    @Override
    public Publisher<String> apply(ServerWebExchange serverWebExchange, String originBody) {
        String newBody = handlerReqBody(serverWebExchange,originBody);
        return Mono.just(newBody);
    }
}
